package com.yuyou.tas.report.service.impl;

import com.yuyou.tas.report.mapper.ExamModelReportKnowledgeIMapper;
import com.yuyou.tas.report.mapper.StudentReportMapper;
import com.yuyou.tas.report.service.IExamModelReportService;
import com.yuyou.tas.report.service.IExamModelService;
import com.yuyou.tas.report.service.IStudentReportService;
import com.yuyou.tas.report.vo.resp.QuesAvgByHardVo;
import com.yuyou.tas.service.api.lesson.entity.LessonClass;
import com.yuyou.tas.service.api.lesson.entity.Student;
import com.yuyou.tas.service.api.lesson.service.LessonClassAPI;
import com.yuyou.tas.service.api.lesson.service.StudentAPI;
import com.yuyou.tas.service.api.report.dto.*;
import com.yuyou.tas.service.api.report.entity.ExamModel;
import com.yuyou.tas.service.api.report.entity.ExamModelComment;
import com.yuyou.tas.service.api.report.entity.ExamModelReport;
import com.yuyou.tas.service.api.report.vo.QuesResultVo;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.enums.report.ExamModelEnums;
import com.yuyou.tas.util.exception.BusinessException;
import com.yuyou.tas.util.tool.BeanUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class StudentReportServiceImpl implements IStudentReportService{

	@Autowired
	private StudentReportMapper studentReportMapper;
	
	@Autowired
	private IExamModelService examModelService;
	@Autowired
	private IExamModelReportService examModelReportService;
	@Autowired
	private LessonClassAPI lessonClassAPI;
	@Autowired
	private StudentAPI studentAPI;

	@Autowired
	private ExamModelReportKnowledgeIMapper examModelReportKnowledgeIMapper;

	@Override
	public int findReportStudentCount(Pagination<ReportStudentDTO> queryPgn) {
		return studentReportMapper.findReportStudentCount(queryPgn);
	}

	@Override
	public List<ReportStudentDTO> findReportStudentPageList(
			Pagination<ReportStudentDTO> queryPgn) {
		
		List<ReportStudentDTO> list=studentReportMapper.findReportStudentPageList(queryPgn);
		list.forEach(reportStudentDTO ->{
			solveAvg7Rand(reportStudentDTO,false);
		});		
		return list;
	}

	@Override
	public ReportStudentDTO reportInfo(Long examModelReportId,boolean needRank) {
		ReportStudentDTO reportStudentDTO=studentReportMapper.reportInfo(examModelReportId);		
		solveAvg7Rand(reportStudentDTO,needRank);		
		return reportStudentDTO;
	}

	
	/**
	 * 计算平均分和排名
	 * @param reportStudentDTO
	 * @param needRank
	 * @return
	 */
	private ReportStudentDTO solveAvg7Rand(ReportStudentDTO reportStudentDTO,boolean needRank){

		ExamModelReport report=examModelReportService.selectByPrimaryKey(reportStudentDTO.getReportId());
		
		//班级平均分
		BigDecimal classAvgScore=studentReportMapper.reportInfoScore(report.getExamModelId(), null,reportStudentDTO.getLessonClassId());
		reportStudentDTO.setClassAvgScore(classAvgScore==null?new BigDecimal(0):classAvgScore.setScale(2,BigDecimal.ROUND_HALF_UP));
		
		//模板平均分
		BigDecimal modelAvgScore=studentReportMapper.reportInfoScore(report.getExamModelId(), null,null);
		reportStudentDTO.setModelAvgScore(modelAvgScore==null?new BigDecimal(0):modelAvgScore.setScale(2,BigDecimal.ROUND_HALF_UP));
		//校区平均分	
		LessonClass lc=lessonClassAPI.selectById(report.getLessonClassId());
		BigDecimal schoolAvgScore=studentReportMapper.reportInfoScore(report.getExamModelId(), lc.getBaseSchoolId(),null);
		reportStudentDTO.setSchoolAvgScore(schoolAvgScore==null?new BigDecimal(0):schoolAvgScore.setScale(2,BigDecimal.ROUND_HALF_UP));
		
		//模板排名
		Integer modelRank=studentReportMapper.reportInfoRank(report.getExamModelId(),null,null,report.getGetScore());
		//模板校区排名
		Integer modelSchoolRank=studentReportMapper.reportInfoRank(report.getExamModelId(),lc.getBaseSchoolId(),null,report.getGetScore());		
		//模板班级排名
		Integer modelClassRank=studentReportMapper.reportInfoRank(report.getExamModelId(),lc.getBaseSchoolId(),null,report.getGetScore());	
		
		if(needRank){
			reportStudentDTO.setModelAvgRank(modelRank+1);
			reportStudentDTO.setSchoolAvgRank(modelSchoolRank+1);
			reportStudentDTO.setClassAvgRank(modelClassRank+1);
		}
		
		return reportStudentDTO;
	}
	
	
	
	
	
	@Override
	public ReportScoreDTO reportScore(Long examModelReportId) {
		ExamModelReport report=examModelReportService.selectByPrimaryKey(examModelReportId);		
		LessonClass lc=lessonClassAPI.selectById(report.getLessonClassId());
		//横线
		List<String>  legendList= Stream.of("全体","校区").collect(Collectors.toList());
		//横坐标
		List<String> xAxis=new ArrayList<String>();	
		//数据
		List<Integer>alltScoreSerieData=new ArrayList<Integer>();
		List<Integer>schooltScoreSerieData=new ArrayList<Integer>();

		List<ReportScoreSerieDTO> series=Stream.of(new ReportScoreSerieDTO("全体",alltScoreSerieData),new ReportScoreSerieDTO("校区",schooltScoreSerieData)).collect(Collectors.toList());
	
		ExamModel examModel=examModelService.selectByPrimaryKey(report.getExamModelId());
		//划分横坐标
		BigDecimal totalScore=examModel.getScore();
		BigDecimal initScore=BigDecimal.valueOf(0);
		int duan=totalScore.intValue()/10;

		//补0
//		xAxis.add("");
//		alltScoreSerieData.add(0);
//		schooltScoreSerieData.add(0);
		
		for(int i=0;i<duan;i++){
			BigDecimal endScore=BigDecimal.valueOf(i*10+10);
			if(i==0){
				xAxis.add("["+initScore+","+endScore+"]");
			}else{
				xAxis.add("("+initScore+","+endScore+"]");
			}
			//查全体
			Integer allNum=studentReportMapper.reportScoreCount(examModel.getId(),null,initScore,endScore);
			alltScoreSerieData.add(allNum);
			//查校区
			Integer schoolNum=studentReportMapper.reportScoreCount(examModel.getId(),lc.getBaseSchoolId(),initScore,endScore);
			schooltScoreSerieData.add(schoolNum);
			initScore=endScore;

		}
		//总分不为10的总数时候
//		int yuScore=totalScore%10;
		BigDecimal yuScore=totalScore.divideAndRemainder(BigDecimal.valueOf(10))[1];		
		if(yuScore.compareTo(new BigDecimal(0))!=0){
			BigDecimal endScore=examModel.getScore();
			initScore=examModel.getScore().subtract(yuScore).add(BigDecimal.valueOf(1));
			xAxis.add("("+initScore+","+endScore+"]");
			//查全体
			Integer allNum=studentReportMapper.reportScoreCount(examModel.getId(),null,initScore,endScore);
			alltScoreSerieData.add(allNum);
			//查校区
			Integer schoolNum=studentReportMapper.reportScoreCount(examModel.getId(),lc.getBaseSchoolId(),initScore,endScore);
			schooltScoreSerieData.add(schoolNum);
		}
		//查询机构定制评语

		String comment = studentReportMapper.getCommentByParams(report.getAuthOrganizationId() , report.getGetScore().divide(examModel.getScore() , 3 , BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100.0")) , report.getBaseSectionId() , ExamModelEnums.commentType.TOTALITY.getValue() , examModel.getStyle());
		if(StringUtils.isEmpty(comment)){//查询标准评语
			comment = studentReportMapper.getCommentByParams(null , report.getGetScore().divide(examModel.getScore() , 3 , BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100.0")), report.getBaseSectionId() , ExamModelEnums.commentType.TOTALITY.getValue() , examModel.getStyle());

		}
		Student s = studentAPI.selectByPrimaryKey(report.getStudentId());
		if(s != null){
			comment = s.getName()+comment;
		}
		return new ReportScoreDTO(xAxis,legendList,series,report.getGetScore(),examModel.getScore(),comment);
	}

	@Override
	public List<ReportHardDTO> reportHard(Long reportId) {

		ExamModelReport report=examModelReportService.selectByPrimaryKey(reportId);
		if(report == null){throw new BusinessException("没有该报告信息"); }

		List<QuesAvgByHardVo> allAvg = studentReportMapper.getAvgByHard(report.getExamModelId());
		List<QuesAvgByHardVo> stuAvg = studentReportMapper.getStuAvgByHard(report.getStudentId() , report.getExamModelId() ,report.getLessonClassId());

		List<ReportHardDTO> list = new ArrayList<>();

		stuAvg.forEach(stu -> allAvg.forEach(all -> {
			if(stu.getHard().equals(all.getHard())){
				ReportHardDTO r = new ReportHardDTO();
				r.setStuAvg(stu.getAvg());
				r.setAllAvg(all.getAvg());
				r.setHard(stu.getHard());
				r.setScore(stu.getScore());
				list.add(r);
			}
		}));

		List<ReportHardDTO> lastList = new ArrayList<>();
		ReportHardDTO easy = new ReportHardDTO(BigDecimal.ZERO,BigDecimal.ZERO,1,"",BigDecimal.ZERO);
		ReportHardDTO middle = new ReportHardDTO(BigDecimal.ZERO,BigDecimal.ZERO,2,"",BigDecimal.ZERO);
		ReportHardDTO hard = new ReportHardDTO(BigDecimal.ZERO,BigDecimal.ZERO,3,"",BigDecimal.ZERO);

		list.forEach(reportHardDTO -> {
			if(reportHardDTO.getHard() < 3){
				easy.setAllAvg(easy.getAllAvg().add(reportHardDTO.getAllAvg()));
				easy.setScore(reportHardDTO.getScore().add(easy.getScore()));
				easy.setStuAvg(easy.getStuAvg().add(reportHardDTO.getStuAvg()));
			}else if(reportHardDTO.getHard() == 3){
				middle.setAllAvg(middle.getAllAvg().add(reportHardDTO.getAllAvg()));
				middle.setScore(reportHardDTO.getScore().add(middle.getScore()));
				middle.setStuAvg(middle.getStuAvg().add(reportHardDTO.getStuAvg()));
			}else{
				hard.setAllAvg(hard.getAllAvg().add(reportHardDTO.getAllAvg()));
				hard.setScore(reportHardDTO.getScore().add(hard.getScore()));
				hard.setStuAvg(hard.getStuAvg().add(reportHardDTO.getStuAvg()));

			}
		});

		lastList.add(easy);
		lastList.add(middle);
		lastList.add(hard);
		lastList.forEach(reportHardDTO -> {

			if(reportHardDTO.getScore().compareTo(BigDecimal.ZERO) == 0){//没有对应难度的题目
				reportHardDTO.setStandard("无");
			}else if(reportHardDTO.getStuAvg().compareTo(reportHardDTO.getScore()) == 0){//等于总分
				reportHardDTO.setStandard("优秀");
			}else{
				int result = reportHardDTO.getStuAvg().compareTo(reportHardDTO.getAllAvg());
				switch (result){
					case -1:
						reportHardDTO.setStandard("待提高");
						break;
					case 0:
						reportHardDTO.setStandard("良好");
						break;
					case 1:
						reportHardDTO.setStandard("良好");
						break;
					default:break;
				}
			}
			reportHardDTO.setStuAvg(reportHardDTO.getStuAvg().setScale(2, BigDecimal.ROUND_HALF_UP));
			reportHardDTO.setAllAvg(reportHardDTO.getAllAvg().setScale(2, BigDecimal.ROUND_HALF_UP));
		});
		return lastList;
	}

	@Override
	public ReportQuesDTO reportQues(Long reportId) {

		ExamModelReport report=examModelReportService.selectByPrimaryKey(reportId);
		if(report == null){throw new BusinessException("没有该报告信息"); }

		List<QuesResultVo> list = studentReportMapper.getStuQues(report.getStudentId(), report.getExamModelId() , report.getLessonClassId());
		ReportQuesDTO reportQuesDTO = new ReportQuesDTO();
		BigDecimal avg = studentReportMapper.reportInfoScore(report.getExamModelId(), null,null);

		list.forEach(quesResultVo -> quesResultVo.setScoringRate(quesResultVo.getScoringRate().setScale(3, BigDecimal.ROUND_HALF_UP)));
		final BigDecimal[] stuScore = {BigDecimal.ZERO};
				list.forEach(quesResultVo -> stuScore[0] = stuScore[0].add(quesResultVo.getGetScore()));
		final BigDecimal[] score = {BigDecimal.ZERO};
				list.forEach(quesResultVo -> score[0] = score[0].add(quesResultVo.getScore()));

		reportQuesDTO.setQuesCount(list.size());
		reportQuesDTO.setAvg(avg == null ? BigDecimal.valueOf(0.0):avg.setScale(2, BigDecimal.ROUND_HALF_UP));
		reportQuesDTO.setStuScore(stuScore[0]);
		reportQuesDTO.setScore(score[0]);
		reportQuesDTO.setQuesList(list);
		return reportQuesDTO;
	}

	@Override
	public ReportKnow reportKnow(Long studentId, Long examModelId, Long lessonClassId , ExamModelReport report) {
		List<ReportKnowDTO> reportKnowList = studentReportMapper.reportKnow(studentId, examModelId, lessonClassId);
		List<ReportKnowDTO> reportKnowAvgScoreList = studentReportMapper.avgScoreOfKnow(examModelId);
		Map<String, ReportKnowDTO> avgScoreOfKnow = BeanUtils.toMap(reportKnowAvgScoreList, "knowledge");

		ExamModel examModel = examModelService.selectByPrimaryKey(examModelId);
		Student student = studentAPI.selectByPrimaryKey(studentId);
		//查询机构定制评语
		List<ExamModelComment> comments = studentReportMapper.getCommentEntityByParams(report.getAuthOrganizationId() , report.getBaseSectionId() , ExamModelEnums.commentType.KNOWLEDGE.getValue() , examModel.getStyle());
		if(CollectionUtils.isEmpty(comments) || comments.size() < 1){//查询标准评语
			comments = studentReportMapper.getCommentEntityByParams(null , report.getBaseSectionId() , ExamModelEnums.commentType.KNOWLEDGE.getValue() , examModel.getStyle());
		}

		for(ReportKnowDTO reportKnowDTO : reportKnowList){
			reportKnowDTO.setScoringRate(reportKnowDTO.getGetScore().divide(reportKnowDTO.getScore(), 3, BigDecimal.ROUND_HALF_UP));
			reportKnowDTO.setAvgScore(avgScoreOfKnow.get(reportKnowDTO.getKnowledge()).getAvgScore());
		}
		String comment = setComment(reportKnowList , comments , student == null ? "":student.getName());
		ReportKnow reportKnow = new ReportKnow(report.getId() , comment , reportKnowList);
		return reportKnow;
	}

	@Override
	public ReportKnowI reportKnowI(Long studentId, Long examModelId, Long lessonClassId , ExamModelReport report) {
		List<ReportKnowIDTO> reportKnowIList = examModelReportKnowledgeIMapper.reportKonwI(report.getId(), examModelId);

		// 评语构造
		List<ReportKnowDTO> reportKnowList = new ArrayList<>(reportKnowIList.size());
		for (ReportKnowIDTO reportKnowI : reportKnowIList) {
			ReportKnowDTO reportKnow = new ReportKnowDTO();
			reportKnow.setKnowledge(reportKnowI.getKnowledgeI());
			reportKnow.setScoringRate(reportKnowI.getSelfScoringRate());
			reportKnowList.add(reportKnow);
		}

		ExamModel examModel = examModelService.selectByPrimaryKey(examModelId);
		Student student = studentAPI.selectByPrimaryKey(studentId);
		// 查询机构定制评语
		List<ExamModelComment> comments = studentReportMapper.getCommentEntityByParams(report.getAuthOrganizationId() , report.getBaseSectionId() , ExamModelEnums.commentType.KNOWLEDGE.getValue() , examModel.getStyle());
		if(CollectionUtils.isEmpty(comments) || comments.size() < 1){//查询标准评语
			comments = studentReportMapper.getCommentEntityByParams(null , report.getBaseSectionId() , ExamModelEnums.commentType.COLUMNAR.getValue() , examModel.getStyle());
		}
		String comment = setComment(reportKnowList , comments , student == null ? "":student.getName());
		ReportKnowI reportKnowI = new ReportKnowI(report.getId() , comment , reportKnowIList);
		return reportKnowI;
	}

	/**
	 * 处理合并知识点评语
	 * @param reportKnowList
	 * @param comments
	 * @param studentName
	 * @return
	 */
	public String setComment(List<ReportKnowDTO> reportKnowList ,List<ExamModelComment> comments,  String studentName){
		final String[] commentStr = {""};
		comments.forEach(examModelComment -> {
			final String[] knowsName = {""};
			BigDecimal min = new BigDecimal(examModelComment.getMin_interval()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
			BigDecimal max = new BigDecimal(examModelComment.getMax_interval()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
			reportKnowList.forEach(reportKnowDTO -> {
  				if(reportKnowDTO.getScoringRate().compareTo(min) > 0
						&& reportKnowDTO.getScoringRate().compareTo(max) <= 0){
					knowsName[0] = knowsName[0] + reportKnowDTO.getKnowledge() + "、";
				}
			});
			if(!StringUtils.isEmpty(knowsName[0])){
				commentStr[0] = commentStr[0] + knowsName[0].substring(0,knowsName[0].length() - 1) + examModelComment.getContent();
			}
		});
		return studentName + "同学的" + commentStr[0];
	}
}
